package com.dengqi.mymodule.activity.permission;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.dengqi.mymodule.BaseActivity;
import com.dengqi.mymodule.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * Permission原生使用
 */
public class PermissionActivity extends BaseActivity {

    //只申请读还是不能写
    final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA};
    final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 10;
    final String permission = Manifest.permission.WRITE_CALENDAR;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
    }

    public void onBtn1(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SharedPreferences sharedPreferences = getSharedPreferences("permission", MODE_PRIVATE);
            boolean isFirst = sharedPreferences.getBoolean("isFirst", true);
            /**
             * 数组转成可remove的集合的迭代器（iterator）
             */
            List<String> persList = new ArrayList<>();
            for (String s : permissions) {
                persList.add(s);
            }
            /**
             * 循环迭代器 如何授权就删除
             */
            List<String> forbidList = new ArrayList<>(); //禁止的权限
            Iterator<String> iterator = persList.iterator();
            while (iterator.hasNext()) {
                String permiss = iterator.next();
                if (ContextCompat.checkSelfPermission(this, permiss) == PackageManager.PERMISSION_GRANTED) {
                    iterator.remove();
                    continue;
                }
                //是否提示申请权限
                /**
                 * 第一次打开App时	false
                 * 上次弹出权限点击了禁止（但没有勾选“下次不在询问”）	true
                 * 上次选择禁止并勾选：下次不在询问	false
                 */
                boolean showrequest = ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, permiss);
                if (!isFirst && !showrequest) {
                    iterator.remove();
                    forbidList.add(permiss);
                }
            }
            Log.e("--->", persList.toString());
            Log.e("--->", forbidList.toString());

            ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_REQUEST_CALL_PHONE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("isFirst", false);
            editor.apply();
            /**
             * 作用1：勾选“下次不在询问”并拒绝
             * 作用2：防止:允许后 手动点拒绝或询问
             */
            if (forbidList.size() > 0) {
                toAppDetailSettingIntent();
                Toast.makeText(this, "禁止" + forbidList.toString(), Toast.LENGTH_SHORT).show();
            }

        }
    }


    public void onBtn2(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                SharedPreferences sharedPreferences = getSharedPreferences("permission", MODE_PRIVATE);
                boolean isFirst2 = sharedPreferences.getBoolean("isFirst2", true);
                //是否提示申请权限
                /**
                 * 第一次打开App时	false
                 * 上次弹出权限点击了禁止（但没有勾选“下次不在询问”）	true
                 * 上次选择禁止并勾选：下次不在询问	false
                 */
                boolean showrequest = ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, permission);
                if (isFirst2 || showrequest) {
                    ActivityCompat.requestPermissions(this, new String[]{permission}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("isFirst2", false);
                    editor.commit();
                } else {
                    toAppDetailSettingIntent();
                }
            } else {
                Toast.makeText(this, "do...", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void onBtn3(View view){
        startActivity(new Intent(this, TestPermissionActivity.class));
    }

    public void onBtn4(View view){
        startActivity(new Intent(this, StaticPermissionActivity.class));
    }

    public void onBtn5(View view){
        startActivity(new Intent(this, RxPermissionActivity.class));
    }

    private void toAppDetailSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            int count = 0;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    count++;
                    Toast.makeText(this, "" + "权限" + permissions[i] + "申请成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "" + "权限" + permissions[i] + "申请失败", Toast.LENGTH_SHORT).show();
                }
            }
            if(count == permissions.length){
                Toast.makeText(this, "do...", Toast.LENGTH_SHORT).show();

            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

